package com.abbas.smartCity;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.abbas.smartCity.bean.UserInfoBean;
import com.abbas.smartCity.retroft.Api;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.time.Duration;
import java.util.Objects;

import okhttp3.OkHttpClient;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 应用全局进程类
 * SP持久化存储在此初始化
 * 网络访问初始化与网络基础地址在此
 * 用户信息存储在此/非持久化存储
 */
public class App extends Application {

    /**
     * 全局上下文
     */
    @SuppressLint("StaticFieldLeak")
    private static Context context;
    /**
     * 全局唯一SharedPreferences存储
     */
    private static SharedPreferences sharedPreferences;
    /**
     * 网络访问基础地址
     */
    private static String BASE_URL = null;
    /**
     * retrofit动态代理接口
     */
    private static Api api = null;
    /**
     * 用户信息
     */
    private static UserInfoBean.UserBean user = null;

    /**
     * OkHttp封装 线程切换使用
     */
    private static final Handler handler = new Handler(Looper.getMainLooper());

    public static final Gson gson = new Gson();

    public static final JSONObject jsonObj = new JSONObject();


    @Override
    public void onCreate() {
        super.onCreate();

        context = this;
        sharedPreferences = getSharedPreferences("sp", Context.MODE_PRIVATE);

        BASE_URL = "http://" + sharedPreferences.getString("port", "");

        if (!TextUtils.equals("http://", BASE_URL)) {
            createApi();
        }

    }

    /**
     * 重置Retrofit的动态代理Api对象
     */
    public static void createApi() {
        //新建一个拦截器
        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)//设置基础地址
                .addConverterFactory(GsonConverterFactory.create())//设置响应结果的Json String自动转换为实体类
                .client(new OkHttpClient.Builder()//添加一个Client 在Client当中启用拦截器
                        .connectTimeout(Duration.ofSeconds(10))
                        .callTimeout(Duration.ofSeconds(10))
                        .retryOnConnectionFailure(true)
                        .addInterceptor(chain -> {
                            Log.i("Net Call ---> ", chain.request().url().toString());
                            //拦截除了登录以外的所有接口，并在所有接口请求当中添加Token令牌
                            if (TextUtils.equals(BASE_URL + "/prod-api/api/login", chain.request().url().toString())) {
                                return chain.proceed(chain.request());//登录请求则不拦截，直接process(放行)请求
                            } else {
                                //其他请求则拦截，并且添加Token令牌
                                return chain.proceed(chain.request()
                                        .newBuilder()
                                        .addHeader("Authorization", Objects.requireNonNull(sharedPreferences.getString("token", "")))//添加令牌
                                        .build());
                            }
                        })
                        .build())
                .build();

        api = retrofit.create(Api.class);
    }

    public static UserInfoBean.UserBean getUser() {
        return user;
    }

    public static void setUser(UserInfoBean.UserBean user) {
        App.user = user;
    }

    public static void setApi(Api api) {
        App.api = api;
    }

    public static Api getApi() {
        return api;
    }

    public static void setBaseUrl(String baseUrl) {
        BASE_URL = "http://" + baseUrl;
    }

    public static String getBaseUrl() {
        return BASE_URL;
    }

    public static SharedPreferences getSharedPreferences() {
        return sharedPreferences;
    }

    public static Context getContext() {
        return context;
    }

    public static Handler getHandler() {
        return handler;
    }
}
